<script setup lang="ts">
  import { ref, watch, onMounted, computed } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { useForm } from '@/hooks/arco/useForm';
  import { queryBaseAreaInfo, queryDictionary } from '@/api/platform';
  import { queryInstStations } from '@/api/structure-management/station';
  import { createElder, updateElder } from '@/api/customerManagement/profile';
  import * as Lodash from 'lodash';
  import { validateIdCard } from '@/utils/validate';
  import { fillData } from '@/views/lhj-v1/util';
  import { useSelectOption } from '@/hooks/arco/useSelectOption';

  const loading = ref(false);
  const emits = defineEmits(['cancel', 'save']);
  const props = withDefaults(
    defineProps<{
      data?: any;
      visible?: boolean;
      title?: string;
      type: 'add' | 'edit';
    }>(),
    {
      visible: false,
      title: '客户信息',
    }
  );

  const baseNameMap = {
    elderName: {
      key: 'elderName',
      label: '客户姓名',
      placeholder: '请输入客户姓名',
    },
    idCardType: {
      key: 'idCardType',
      label: '证件类型',
      placeholder: '请选择证件类型',
    },
    idCardNo: {
      key: 'idCardNo',
      label: '证件号码',
      placeholder: '请输入证件号码',
    },
    gender: { key: 'gender', label: '客户性别', placeholder: '请选择客户性别' },
    birthdate: {
      key: 'birthdate',
      label: '出生日期',
      placeholder: '请选择出生日期',
    },
    phone: { key: 'phone', label: '联系电话', placeholder: '请输入联系电话' },
    region: { key: 'region', label: '所在地区', placeholder: '请选择所在地区' },
    province: { key: 'provinceCode', label: '籍贯' },
    city: { key: 'cityCode', label: '籍贯' },
    district: { key: 'districtCode', label: '籍贯' },
    address: {
      key: 'address',
      label: '详细地址',
      placeholder: '请输入详细地址',
    },
    relationStatus: {
      key: 'relationStatus',
      label: '签约状态',
      placeholder: '请选择签约状态',
    },
    station: {
      key: 'stationId',
      label: '关联站点',
      placeholder: '请选择关联站点',
    },
    familyName: {
      key: 'familyName',
      label: '家属姓名',
      placeholder: '请输入家属姓名',
    },
    familyRelation: {
      key: 'familyRelation',
      label: '家属关系',
      placeholder: '请选择家属关系',
    },
    familyPhone: {
      key: 'familyPhone',
      label: '家属电话',
      placeholder: '请输入家属电话',
    },
  };

  const idCardTypeOptions = ref([
    { label: '居民身份证', value: 1 },
    { label: '护照', value: 2 },
    { label: '军官证', value: 3 },
  ]);

  const genderOptions = ref([
    { label: '男', value: 1 },
    { label: '女', value: 2 },
  ]);

  // 签约状态：1=游客，2=签前体验，3=已签约，4=已解约
  const relationStatusOptions = ref([
    { label: '游客', value: 1 },
    { label: '签前体验', value: 2 },
    { label: '已签约', value: 3 },
    { label: '已解约', value: 4 },
  ]);

  const familyRelationOptions = ref([
    { label: '配偶', value: '11' },
    { label: '儿子', value: '12' },
    { label: '女儿', value: '13' },
    { label: '儿媳', value: '14' },
    { label: '女婿', value: '15' },
    { label: '兄弟', value: '16' },
    { label: '姐们', value: '17' },
    { label: '孙子/孙女', value: '18' },
    { label: '其他', value: '99' },
  ]);
  // 关联站点下拉选项（参照 m-station/index.vue 的接口用法）
  const stationOptions = ref<Array<{ label: string; value: string | number }>>(
    []
  );

  // 省市区级联下拉（树形结构）
  const regionOptions = useSelectOption({
    apiFun: queryBaseAreaInfo,
    fieldNames: {
      label: 'label',
      value: 'value',
      children: 'children',
    },
  });

  // 获取站点信息（与 m-station/index.vue 保持一致：传入 page、pageSize，读取 res.list）
  const loadStations = async () => {
    try {
      const page = 1;
      const pageSize = 1000; // 站点通常不多，拉取足够多便于下拉选择
      const res = await queryInstStations(page, pageSize);
      const list = res?.list || res?.data?.list || [];
      stationOptions.value = list.map((item: any) => ({
        label: item.name,
        value: item.id,
      }));
    } catch (error) {
      console.error('获取站点信息失败', error);
      stationOptions.value = [];
    }
  };

  // 获取家属关系字典
  const loadFamilyRelations = async () => {
    try {
      const res = await queryDictionary('relationship');
      if (res?.data && Array.isArray(res.data)) {
        familyRelationOptions.value = res.data.map((item: any) => ({
          label: item.label || item.name,
          value: item.value || item.code,
        }));
      }
    } catch (error) {
      console.error('获取家属关系字典失败', error);
      // 使用默认值作为备用
      familyRelationOptions.value = [
        { label: '父子', value: '1' },
        { label: '母子', value: '2' },
        { label: '父女', value: '3' },
        { label: '母女', value: '4' },
        { label: '配偶', value: '5' },
        { label: '其他', value: '6' },
      ];
    }
  };

  onMounted(() => {
    loadStations();
    loadFamilyRelations();
  });

  const itemForm = useForm({
    state: {
      [baseNameMap.elderName.key]: '',
      [baseNameMap.idCardType.key]: 1,
      [baseNameMap.idCardNo.key]: '',
      [baseNameMap.gender.key]: '',
      [baseNameMap.birthdate.key]: '',
      [baseNameMap.phone.key]: '',
      [baseNameMap.region.key]: [],
      [baseNameMap.address.key]: '',
      [baseNameMap.relationStatus.key]: 1,
      [baseNameMap.station.key]: '',
      [baseNameMap.familyName.key]: '',
      [baseNameMap.familyRelation.key]: '',
      [baseNameMap.familyPhone.key]: '',
    },
    rules: {
      [baseNameMap.elderName.key]: {
        required: true,
        message: baseNameMap.elderName.placeholder,
      },
      [baseNameMap.idCardType.key]: {
        required: true,
        message: baseNameMap.idCardType.placeholder,
      },
      [baseNameMap.idCardNo.key]: {
        required: true,
        message: baseNameMap.idCardNo.placeholder,
      },
      [baseNameMap.gender.key]: {
        required: true,
        message: baseNameMap.gender.placeholder,
      },
      [baseNameMap.birthdate.key]: {
        required: true,
        message: baseNameMap.birthdate.placeholder,
      },
      [baseNameMap.region.key]: {
        required: true,
        message: baseNameMap.region.placeholder,
      },
      [baseNameMap.address.key]: {
        required: true,
        message: baseNameMap.address.placeholder,
      },
      [baseNameMap.relationStatus.key]: {
        required: true,
        message: baseNameMap.relationStatus.placeholder,
      },
      [baseNameMap.station.key]: {
        required: true,
        message: baseNameMap.station.placeholder,
      },
      [baseNameMap.familyName.key]: {
        required: true,
        message: baseNameMap.familyName.placeholder,
      },
      [baseNameMap.familyRelation.key]: {
        required: true,
        message: baseNameMap.familyRelation.placeholder,
      },
      [baseNameMap.familyPhone.key]: {
        required: true,
        message: baseNameMap.familyPhone.placeholder,
      },
    },
  });

  // 解决模板中 v-model 的联合类型推断问题：为各字段提供类型明确的 computed 代理
  const elderNameModel = computed<string>({
    get: () => (itemForm.state[baseNameMap.elderName.key] ?? '') as string,
    set: (val: string) => {
      itemForm.state[baseNameMap.elderName.key] = val as any;
    },
  });

  // 家属关系值的类型转换计算属性，确保字符串类型匹配
  const familyRelationModel = computed<string>({
    get: () => {
      const value = itemForm.state[baseNameMap.familyRelation.key];
      return value === null || value === undefined ? '' : String(value);
    },
    set: (val: string) => {
      itemForm.state[baseNameMap.familyRelation.key] = val;
    },
  });

  const idCardNoModel = computed<string>({
    get: () => (itemForm.state[baseNameMap.idCardNo.key] ?? '') as string,
    set: (val: string) => {
      itemForm.state[baseNameMap.idCardNo.key] = val as any;
    },
  });

  const phoneModel = computed<string>({
    get: () => (itemForm.state[baseNameMap.phone.key] ?? '') as string,
    set: (val: string) => {
      itemForm.state[baseNameMap.phone.key] = val as any;
    },
  });

  const addressModel = computed<string>({
    get: () => (itemForm.state[baseNameMap.address.key] ?? '') as string,
    set: (val: string) => {
      itemForm.state[baseNameMap.address.key] = val as any;
    },
  });

  const familyNameModel = computed<string>({
    get: () => (itemForm.state[baseNameMap.familyName.key] ?? '') as string,
    set: (val: string) => {
      itemForm.state[baseNameMap.familyName.key] = val as any;
    },
  });

  const familyPhoneModel = computed<string>({
    get: () => (itemForm.state[baseNameMap.familyPhone.key] ?? '') as string,
    set: (val: string) => {
      itemForm.state[baseNameMap.familyPhone.key] = val as any;
    },
  });

  const birthdateModel = computed<string | number | Date | undefined>({
    get: () => itemForm.state[baseNameMap.birthdate.key] as any,
    set: (val: string | number | Date | undefined) => {
      itemForm.state[baseNameMap.birthdate.key] = val as any;
    },
  });

  const regionModel = computed<(string | number)[]>({
    get: () => {
      const v = itemForm.state[baseNameMap.region.key];
      return Array.isArray(v) ? (v as (string | number)[]) : [];
    },
    set: (val: (string | number)[]) => {
      itemForm.state[baseNameMap.region.key] = val as any;
    },
  });

  const handleDrawerSave = () => {
    itemForm
      .validate()
      .then(() => {
        loading.value = true;
        let messageText = '新增成功！';
        let apiFunc: any = createElder;
        const jsonData: any = Lodash.cloneDeep(itemForm.state);
        // 将级联选择的省市区写入后端所需字段
        const regionCodes: any[] = jsonData[baseNameMap.region.key] || [];
        if (Array.isArray(regionCodes) && regionCodes.length > 0) {
          jsonData[baseNameMap.province.key] = regionCodes[0] || '';
          jsonData[baseNameMap.city.key] = regionCodes[1] || '';
          jsonData[baseNameMap.district.key] = regionCodes[2] || '';
        }

        if (props.type === 'edit') {
          messageText = '保存成功！';
          apiFunc = updateElder;
          // 编辑客户必须携带 elderId
          if (!jsonData.elderId) {
            const src: any = props.data || {};
            jsonData.elderId = src.elderId || src.id || src.elderID || '';
          }
          if (!jsonData.elderId) {
            Message.warning('缺少客户ID（elderId），无法提交编辑');
            loading.value = false;
            return;
          }
        } else if (props.type !== 'add') {
          return;
        }

        apiFunc(jsonData)
          .then(() => {
            Message.success(messageText);
            itemForm.backToInit();
            emits('cancel');
            emits('save');
            // 如果是编辑操作，触发update事件通知父组件刷新详情数据
            if (props.type === 'edit' && jsonData.elderId) {
              emits('update', { elderId: jsonData.elderId });
            }
          })
          .catch((error: any) => {
            Message.error(error.message || '操作失败');
          })
          .finally(() => {
            loading.value = false;
          });
      })
      .catch((err) => {
        console.error(err);
      });
  };

  watch(
    () => props.data,
    (newVal) => {
      if (newVal) {
        const data = Lodash.cloneDeep(newVal);
        fillData(itemForm.state, data);
        // 编辑态回显：将已存的省/市/区代码填充到级联选择器
        const provinceCode = data[baseNameMap.province.key];
        const cityCode = data[baseNameMap.city.key];
        const districtCode = data[baseNameMap.district.key];
        const regionPath = [provinceCode, cityCode, districtCode].filter(
          (e) => !!e
        );
        if (regionPath.length > 0) {
          itemForm.state[baseNameMap.region.key] = regionPath as any;
        }
      }
    },
    { immediate: true, deep: true }
  );

  // 重置表单
  watch(
    () => props.visible,
    (newVal) => {
      if (!newVal) {
        itemForm.resetFields();
      }
    }
  );

  // 实时计算 `性别`、`出生日期`
  watch(
    () => itemForm.state[baseNameMap.idCardNo.key],
    (newVal) => {
      // 确保newVal是字符串类型
      const certNo = String(newVal);
      if (
        certNo &&
        validateIdCard(certNo) &&
        itemForm.state[baseNameMap.idCardType.key] === 1
      ) {
        const gender = parseInt(certNo.substring(16, 17), 10) % 2 === 0 ? 2 : 1;
        itemForm.state[baseNameMap.gender.key] = gender;
        const date = certNo.substring(6, 14);
        itemForm.state[baseNameMap.birthdate.key] = `${date.substring(
          0,
          4
        )}-${date.substring(4, 6)}-${date.substring(6)}`;
      }
    }
  );

  // 重置表单
  watch(
    () => props.visible,
    (newVal) => {
      if (!newVal) {
        itemForm.resetFields();
      }
    }
  );
</script>

<template>
  <div class="m-customer-edit">
    <a-drawer
      :width="400"
      :visible="props.visible"
      unmount-on-close
      @cancel="emits('cancel')"
    >
      <template #title>{{ props.title }}</template>
      <div>
        <a-form v-bind="itemForm.bindProps" layout="vertical">
          <!-- 客户姓名 -->
          <a-form-item
            :field="baseNameMap.elderName.key"
            :label="baseNameMap.elderName.label"
          >
            <a-input
              v-model="elderNameModel"
              :placeholder="baseNameMap.elderName.placeholder"
              allow-clear
            />
          </a-form-item>

          <!-- 证件类型 -->
          <a-form-item
            :field="baseNameMap.idCardType.key"
            :label="baseNameMap.idCardType.label"
          >
            <a-select
              v-model="itemForm.state[baseNameMap.idCardType.key]"
              :placeholder="baseNameMap.idCardType.placeholder"
              allow-clear
            >
              <a-option
                v-for="(item, index) in idCardTypeOptions"
                :key="'cert-' + index"
                :value="item.value"
                :label="item.label"
              />
            </a-select>
          </a-form-item>

          <!-- 证件号码 -->
          <a-form-item
            :field="baseNameMap.idCardNo.key"
            :label="baseNameMap.idCardNo.label"
          >
            <a-input
              v-model="idCardNoModel"
              :max-length="18"
              :placeholder="baseNameMap.idCardNo.placeholder"
              allow-clear
            />
          </a-form-item>

          <!-- 客户性别 -->
          <a-form-item
            :field="baseNameMap.gender.key"
            :label="baseNameMap.gender.label"
          >
            <a-select
              v-model="itemForm.state[baseNameMap.gender.key]"
              :placeholder="baseNameMap.gender.placeholder"
              allow-clear
            >
              <a-option
                v-for="(item, index) in genderOptions"
                :key="'gender-' + index"
                :value="item.value"
                :label="item.label"
              />
            </a-select>
          </a-form-item>

          <!-- 出生日期 -->
          <a-form-item
            :field="baseNameMap.birthdate.key"
            :label="baseNameMap.birthdate.label"
          >
            <a-date-picker
              v-model="birthdateModel"
              style="width: 100%"
              :placeholder="baseNameMap.birthdate.placeholder"
              allow-clear
            />
          </a-form-item>

          <!-- 联系电话 -->
          <a-form-item
            :field="baseNameMap.phone.key"
            :label="baseNameMap.phone.label"
          >
            <a-input
              v-model="phoneModel"
              :placeholder="baseNameMap.phone.placeholder"
              allow-clear
            />
          </a-form-item>

          <!-- 所在地区 -->
          <a-form-item
            :field="baseNameMap.region.key"
            :label="baseNameMap.region.label"
          >
            <a-cascader
              v-model="regionModel"
              expand-trigger="hover"
              path-mode
              allow-clear
              v-bind="regionOptions.bindProps"
              :placeholder="baseNameMap.region.placeholder"
            />
          </a-form-item>

          <!-- 详细地址 -->
          <a-form-item
            :field="baseNameMap.address.key"
            :label="baseNameMap.address.label"
          >
            <a-input
              v-model="addressModel"
              :placeholder="baseNameMap.address.placeholder"
              allow-clear
            />
          </a-form-item>

          <!-- 签约状态 -->
          <a-form-item
            :field="baseNameMap.relationStatus.key"
            :label="baseNameMap.relationStatus.label"
          >
            <a-select
              v-model="itemForm.state[baseNameMap.relationStatus.key]"
              :placeholder="baseNameMap.relationStatus.placeholder"
              allow-clear
            >
              <a-option
                v-for="(item, index) in relationStatusOptions"
                :key="'contract-' + index"
                :value="item.value"
                :label="item.label"
              />
            </a-select>
          </a-form-item>

          <!-- 关联站点 -->
          <a-form-item
            :field="baseNameMap.station.key"
            :label="baseNameMap.station.label"
          >
            <a-select
              v-model="itemForm.state[baseNameMap.station.key]"
              :placeholder="baseNameMap.station.placeholder"
              allow-clear
            >
              <a-option
                v-for="(item, index) in stationOptions"
                :key="'station-' + index"
                :value="item.value"
                :label="item.label"
              />
            </a-select>
          </a-form-item>

          <!-- 家属姓名 -->
          <a-form-item
            :field="baseNameMap.familyName.key"
            :label="baseNameMap.familyName.label"
          >
            <a-input
              v-model="familyNameModel"
              :placeholder="baseNameMap.familyName.placeholder"
              allow-clear
            />
          </a-form-item>

          <!-- 家属关系 -->
          <a-form-item
            :field="baseNameMap.familyRelation.key"
            :label="baseNameMap.familyRelation.label"
          >
            <a-select
              v-model="familyRelationModel"
              :placeholder="baseNameMap.familyRelation.placeholder"
              allow-clear
            >
              <a-option
                v-for="(item, index) in familyRelationOptions"
                :key="'relation-' + index"
                :value="item.value"
                :label="item.label"
              />
            </a-select>
          </a-form-item>

          <!-- 家属电话 -->
          <a-form-item
            :field="baseNameMap.familyPhone.key"
            :label="baseNameMap.familyPhone.label"
          >
            <a-input
              v-model="familyPhoneModel"
              :placeholder="baseNameMap.familyPhone.placeholder"
              allow-clear
            />
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <ae-button purpose="cancel" @click="emits('cancel')">取消</ae-button>
        <ae-button purpose="save" @click="handleDrawerSave">保存</ae-button>
      </template>
    </a-drawer>
  </div>
</template>

<style lang="less" scoped>
  .m-customer-edit {
  }
</style>
